package com.emuporium.gymrat.server.routine;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.emuporium.gymrat.server.data.Routine;
import com.emuporium.gymrat.server.data.RoutineDB;

//use get for viewing the routine to modify, post to submit modifications
@SuppressWarnings("serial")
public class RoutineModifySubmitServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// check if these conflict with routine, if so update routine, assuming
		// these arent null

		String newName = request.getParameter("newName");
		String newDesc = request.getParameter("newDesc");
		String newAuthor = request.getParameter("newAuthor");
		int primary, secondary;
		try {
			primary = new Integer(request.getParameter("primary"));
		} catch (NumberFormatException e) {
			primary = -1;
		}
		try {
			secondary = new Integer(request.getParameter("secondary"));
		} catch (NumberFormatException e) {
			secondary = -1;
		}
		boolean shared = Boolean.parseBoolean((request
				.getParameter("sharecheck")));
		boolean delete = Boolean.parseBoolean((request.getParameter("delete")));

		Integer routineId = new Integer(request.getParameter("id"));

		if (routineId != null) {
			Routine routine = new Routine();
			routine.setName(newName);
			routine.setDescription(newDesc);
			routine.setAuthor(newAuthor);
			routine.setId(routineId);
			routine.setPrimary(primary);
			routine.setSecondary(secondary);
			routine.setShared(shared);

			int result = 0;

			if (delete) {
				result = RoutineDB.delete(routine);
				if (result > 0)
					request.setAttribute("result", "Deleted Routine "
							+ routine.getName());

			} else {
				result = RoutineDB.update(routine);
				if (result > 0)
					request.setAttribute("result", "Updated Routine "
							+ routine.getName());
			}

			if (result == 0)
				request.setAttribute("result", "Failed to modify routine");
		}

		request.setAttribute("redirecturl", "/routine/list");
		String url = "/includes/redirect.jsp";
		RequestDispatcher dispatcher = getServletContext()
				.getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}
}
